use axum::{
    body::Body,
    extract::{Request, State},
    http::{HeaderMap, StatusCode},
    response::Response,
    Json,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tracing::{error, warn};
use rand::Rng;

use crate::message_router::{MessageRouter, RouteRule};

// 简化版网关代理配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GatewayConfig {
    pub max_connections: usize,
    pub connection_timeout: u64,
    pub request_timeout: u64,
    pub circuit_breaker_threshold: u32,
}

// 代理统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProxyStats {
    pub total_requests: u64,
    pub success_requests: u64,
    pub failed_requests: u64,
    pub current_connections: usize,
}

// 熔断器状态
#[derive(Debug, Clone)]
pub enum CircuitBreakerState {
    Closed,
    Open,
    HalfOpen,
}

// 简化版熔断器
#[derive(Debug)]
pub struct CircuitBreaker {
    pub service_name: String,
    pub state: CircuitBreakerState,
    pub failure_count: u32,
    pub threshold: u32,
    pub last_failure_time: Option<std::time::Instant>,
}

impl CircuitBreaker {
    pub fn new(service_name: String, threshold: u32) -> Self {
        Self {
            service_name,
            state: CircuitBreakerState::Closed,
            failure_count: 0,
            threshold,
            last_failure_time: None,
        }
    }

    pub fn can_request(&self) -> bool {
        match self.state {
            CircuitBreakerState::Closed => true,
            CircuitBreakerState::Open => {
                if let Some(last_failure) = self.last_failure_time {
                    if last_failure.elapsed() > Duration::from_secs(30) {
                        return true;
                    }
                }
                false
            }
            CircuitBreakerState::HalfOpen => true,
        }
    }

    pub fn record_success(&mut self) {
        self.failure_count = 0;
        self.last_failure_time = None;
        self.state = CircuitBreakerState::Closed;
    }

    pub fn record_failure(&mut self) {
        self.failure_count += 1;
        self.last_failure_time = Some(std::time::Instant::now());
        
        if self.failure_count >= self.threshold {
            self.state = CircuitBreakerState::Open;
        }
    }
}

// 简化版网关代理服务
pub struct GatewayProxy {
    pub router: Arc<MessageRouter>,
    pub circuit_breakers: Arc<RwLock<HashMap<String, CircuitBreaker>>>,
    pub stats: Arc<RwLock<ProxyStats>>,
    pub config: GatewayConfig,
    pub current_connections: Arc<RwLock<usize>>,
}

impl GatewayProxy {
    pub fn new(router: Arc<MessageRouter>, config: GatewayConfig) -> Self {
        Self {
            router,
            circuit_breakers: Arc::new(RwLock::new(HashMap::new())),
            stats: Arc::new(RwLock::new(ProxyStats {
                total_requests: 0,
                success_requests: 0,
                failed_requests: 0,
                current_connections: 0,
            })),
            config,
            current_connections: Arc::new(RwLock::new(0)),
        }
    }

    // 简化版转发逻辑 - 模拟转发行为
    pub async fn forward_request(&self, request: Request) -> Result<Response, StatusCode> {
        // 检查连接数限制
        {
            let mut current = self.current_connections.write().await;
            if *current >= self.config.max_connections {
                warn!("Connection limit reached: {}/{}", *current, self.config.max_connections);
                return Err(StatusCode::SERVICE_UNAVAILABLE);
            }
            *current += 1;
            self.update_stats(|stats| {
                stats.total_requests += 1;
                stats.current_connections = *current;
            }).await;
        }

        // 匹配路由
        let route_rule = self.router.match_route(request.uri().path(), request.method().as_str()).await
            .ok_or(StatusCode::NOT_FOUND)?;

        // 检查熔断器
        let circuit_breaker_key = format!("{}:{}", route_rule.target, route_rule.id);
        if !self.can_make_request(&circuit_breaker_key).await {
            warn!("Circuit breaker open for: {}", circuit_breaker_key);
            return Err(StatusCode::SERVICE_UNAVAILABLE);
        }

        // 模拟转发处理
        let result = self.simulate_forward(request, &route_rule, &circuit_breaker_key).await;

        // 释放连接
        {
            let mut current = self.current_connections.write().await;
            if *current > 0 {
                *current -= 1;
            }
        }

        result
    }

    async fn simulate_forward(
        &self,
        request: Request,
        route_rule: &RouteRule,
        circuit_breaker_key: &str,
    ) -> Result<Response, StatusCode> {
        // 模拟处理延迟
        tokio::time::sleep(Duration::from_millis(10)).await;

        // 模拟成功率（90%成功）
        let success = rand::thread_rng().gen_bool(0.9);

        if success {
            self.record_circuit_breaker_success(circuit_breaker_key).await;
            self.update_stats(|stats| {
                stats.success_requests += 1;
            }).await;

            // 返回模拟成功响应
            Ok(Response::builder()
                .status(StatusCode::OK)
                .body(Body::from(format!("Forwarded to: {}", route_rule.target)))
                .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?)
        } else {
            self.record_circuit_breaker_failure(circuit_breaker_key).await;
            self.update_stats(|stats| {
                stats.failed_requests += 1;
            }).await;
            Err(StatusCode::BAD_GATEWAY)
        }
    }

    async fn can_make_request(&self, circuit_breaker_key: &str) -> bool {
        let breakers = self.circuit_breakers.read().await;
        if let Some(breaker) = breakers.get(circuit_breaker_key) {
            breaker.can_request()
        } else {
            true
        }
    }

    async fn record_circuit_breaker_success(&self, circuit_breaker_key: &str) {
        let mut breakers = self.circuit_breakers.write().await;
        if let Some(breaker) = breakers.get_mut(circuit_breaker_key) {
            breaker.record_success();
        }
    }

    async fn record_circuit_breaker_failure(&self, circuit_breaker_key: &str) {
        let mut breakers = self.circuit_breakers.write().await;
        let breaker = breakers.entry(circuit_breaker_key.to_string())
            .or_insert_with(|| {
                CircuitBreaker::new(
                    circuit_breaker_key.to_string(),
                    self.config.circuit_breaker_threshold,
                )
            });
        breaker.record_failure();
    }

    async fn update_stats<F>(&self, updater: F)
    where
        F: FnOnce(&mut ProxyStats),
    {
        let mut stats = self.stats.write().await;
        updater(&mut stats);
    }

    // 获取代理统计信息
    pub async fn get_stats(&self) -> ProxyStats {
        self.stats.read().await.clone()
    }
}

// API请求和响应结构
#[derive(Debug, Serialize, Deserialize)]
pub struct ProxyStatsResponse {
    pub stats: ProxyStats,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GatewayConfigResponse {
    pub config: GatewayConfig,
}

// API处理函数
pub async fn get_proxy_stats(
    State(app_state): State<Arc<crate::AppState>>,
) -> Json<ProxyStatsResponse> {
    let stats = app_state.gateway_proxy.get_stats().await;
    Json(ProxyStatsResponse { stats })
}

pub async fn get_gateway_config(
    State(app_state): State<Arc<crate::AppState>>,
) -> Json<GatewayConfigResponse> {
    Json(GatewayConfigResponse {
        config: app_state.gateway_proxy.config.clone(),
    })
}

// 通配符路由处理
pub async fn proxy_handler(
    State(app_state): State<Arc<crate::AppState>>,
    request: Request<Body>,
) -> Result<Response<Body>, StatusCode> {
    app_state.gateway_proxy.forward_request(request).await
}